package com.nulldev.util.sys.wifi;

import java.io.File;
import java.util.ArrayList;

import com.nulldev.util.FinalBypass;
import com.nulldev.util.io.FileUtil;
import com.nulldev.util.java.ProcessUtil;
import com.nulldev.util.os.OSUtil;

public class WiFiUtils {
	
	public static void main(final String[] args) {
		final String int0 = getInterface();
		System.out.println("Interface: " + int0);
		parse();
	}

	// Command: sudo iwlist [interface] scanning
	
	public static boolean isSupported() {
		if (OSUtil.isMac() || OSUtil.isWindows()) {
			return false;
		}
		if (OSUtil.PackageUtil.isPackage("iwlist")) {
			return true;
		}
		return false;
	}
	
	// e*** - Ethernet
	// lo - Loopback
	// wl - WiFi 
	public static String getInterface() {
		final FinalBypass<String> out = new FinalBypass<String>(null);
		final ArrayList<File> files = FileUtil.listFilesForFolderNR(FileUtil.safeCreate("/sys/class/net/"));
		final ArrayList<File> wifiDevices = new ArrayList<File>();
		for (final File dev : files) {
			if (dev.getName().startsWith("wl")) {
				wifiDevices.add(dev);
			}
		}
		if (wifiDevices.size() == 0) {
			return "devices.none";
		}
		if (wifiDevices.size() == 1) {
			out.setObject(wifiDevices.get(0).getName());
		}else {
			// AHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH, waiting for eSelector
			out.setObject(wifiDevices.get(0).getName());
		}
		return out.getObject();
	}
	
	public static void parse() {
		if (!isSupported()) {
			return;
		}
		final String command = "iwlist " + getInterface() + " scanning | egrep 'Cell |Encryption|Quality|Last beacon|ESSID'";
		System.out.println(command);
		OSUtil.PackageUtil.elevateActive(command, new ProcessUtil.ProcessUtilRead() {
			
			@Override
			public void onRead(String input) {
				System.out.println(input);
			}
		});
	}
}
